#!/bin/sh

if [ $(id -u) -ne 0 ]; then
  echo "Installer must be run with root privileges (sudo)."
  exit 1
fi

function backupAndReplace {
  if [ -e $1 ]; then
    mv $1 $1.bak
  fi
  sed -e s/__USER__/$(basename ~)/g < $2 > $1
  chown $(basename ~):$(basename ~) $1
}

echo "### INSTALLING DELUGE ..."
aptitude install -y deluged deluge-console python-setuptools

echo "### STOPPING DELUGE ..."
/etc/init.d/deluged stop

echo "### INSTALLING FLEXGET ..."
python -V 2>&1 | grep "2\.6"
if [ $? -eq 0 ]; then
  wget http://download.flexget.com/unstable/FlexGet-1.0r1262-py2.6.egg -O /tmp/FlexGet.egg
else
  wget http://download.flexget.com/unstable/FlexGet-1.0r1262-py2.5.egg -O /tmp/FlexGet.egg
fi
easy_install /tmp/FlexGet.egg

echo "### COPYING DELUGE CUSTOM CONFIGURATION FILES ..."
backupAndReplace ~/.config/deluge/core.conf /usr/share/htpc-utils/confs/core.conf
backupAndReplace ~/.config/deluge/execute.conf /usr/share/htpc-utils/confs/execute.conf
backupAndReplace /etc/init.d/deluged /usr/share/htpc-utils/scripts/deluged
update-rc.d deluged defaults

echo "### COPYING FLEXGET CUSTOM CONFIGURATION FILE ..."
backupAndReplace ~/.flexget/config.yml /usr/share/htpc-utils/confs/config.yml

echo "### ACTIVATING HOURLY SUBTITLE AUTO-DOWNLOADING ..."
cp /usr/share/htpc-utils/scripts/sub-daemon.sh /etc/cron.hourly/

echo "### CREATING /data TREE STRUCTURE ..."
mkdir -p /data/deluge/tmp
mkdir -p /data/deluge/torrents
mkdir -p /data/hotstuff
mkdir -p /data/store/Games
mkdir -p /data/store/Movies
mkdir -p /data/store/Music
mkdir -p /data/store/Series

echo "### CHANGING OWNER OF THE /data TREE STRUCTURE ..."
chown $(basename ~):$(basename ~) -R /data

echo "### STARTING DELUGE ..."
/etc/init.d/deluged start

echo "* Customize the downloaded series with the file ~/.flexget/config.yml"

